package com.guli.auth.service.impl;
/*
 * @Author 罗
 * @date 2020/10/18 - 2:47 下午
 */

import com.guli.auth.feign.AliServiceFeignClient;
import com.guli.auth.service.MessageService;
import com.guli.auth.util.Generate4BitCode;
import com.guli.common.utils.R;
import com.guli.mall.serviceBase.globalException.MallException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.guli.common.constant.AuthServerConstant.VERIFICATION_CODE_PREFIX;
import static com.guli.common.pojo.vo.StatusCodeEnum.FREQUENTLY_SEND_VERIFICATION_CODE;

@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    AliServiceFeignClient aliServiceFeignClient;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendMessageAndPutIntoRedis(String phoneNumber) {

        // 获取剩余过期时间
        Long expire = stringRedisTemplate.getExpire(VERIFICATION_CODE_PREFIX + phoneNumber);

        /**
         * 防止一个手机号在 60s 多次发送验证码
         * */
        if (!ObjectUtils.isEmpty(expire) && expire > 0 && TimeUnit.SECONDS.toSeconds(5) - expire < 55) {
            throw new MallException(FREQUENTLY_SEND_VERIFICATION_CODE.getCode(), "60秒内不得多次发送验证码");
        }

        String code = Generate4BitCode.generate();

        R r = aliServiceFeignClient.sendMessage(phoneNumber, code);

        if (r.getCode().equals(R.ok().getCode())) {
            stringRedisTemplate.opsForValue().set(VERIFICATION_CODE_PREFIX + phoneNumber, code);
            // 五分钟内有效
            stringRedisTemplate.expire(VERIFICATION_CODE_PREFIX + phoneNumber, 5, TimeUnit.MINUTES);
        } else {
            throw new MallException("发送验证码失败");
        }
    }
}
